<template>
  <div :class="prefixCls">
    <a-alert type='success' banner message="源端点值为请求头origin-endpoint的值, 如果匹配则采用当前域名, 如果源端点为空则为默认值, "
      class="file-config-alert" />

    <BasicForm @register="registerForm" @submit="handleSubmit" :class="prefixCls">
      <template #addEndpointValue="{ model, field }">
        <a-input v-model:value="model[field]" :placeholder="getEndpointValuePlaceholder(field)"
          style="width: calc(100% - 40px)" allowClear />
        <MinusCircleOutlined v-if="count > 1" class="dynamic-delete-button" @click="handleRemoveDomain(field)" />
      </template>

      <template #addDomain="{ model, field }">
        <a-input v-model:value="model[field]" :placeholder="getDomainPlaceholder(field)" style="width: calc(100% - 40px)"
          allowClear />
        <MinusCircleOutlined v-if="count > 1" class="dynamic-delete-button" @click="handleRemoveDomain(field)" />
      </template>

      <template #formFooter>
        <div style="width: calc(100%); margin-left: 100px; margin-right: 40px; display: flex; justify-content: center;">
          <a-button type="dashed" style="width: 95%; align-items: center; margin-bottom: 10px;" @click="handleAddDomain">
            <PlusOutlined />
            添加
          </a-button>
        </div>
        <a-button :class="prefixCls + '-submit'" @click="handleSubmit" type="primary" :loading="loading"
          style="margin-right: 0.9rem">
          保存
        </a-button>
        <a-button v-if="isSensitive" @click="handleShowSensitive" type="primary" style="margin-right: 0.9rem">查看</a-button>
      </template>
    </BasicForm>
    <VerifyModal @register="registerVerifyModal" :submitCallback="handleSubmitVerify"/>
  </div>
</template>
<script lang="ts" setup>
import {ref} from 'vue'
import {BasicForm} from '/@/components/Form/index';
import {MinusCircleOutlined, PlusOutlined} from '@ant-design/icons-vue';
import {ConfigFormProps, useConfigForm} from '/@/hooks/my/useConfigForm'
import {useDesign} from '/@/hooks/web/useDesign';
import {useAttrs} from '/@/hooks/core/useAttrs';
import {useMessage} from '/@/hooks/web/useMessage';
import {defHttp} from '/@/utils/http/axios';
import {VerifyModal} from '/@/components/BizVerify';
import {rules} from '/@/utils/helper/validator';
import {useModal} from '/@/components/Modal';
import {FormSchema} from '/@/components/Table';

const emit = defineEmits(['query-success'])

const domainFormSchema: FormSchema[] = [
  {
    field: 'domainDivider',
    label: "端点域名设置",
    component: "Divider"
  },
  {
    field: 'endpointValue1',
    label: '源端点1',
    component: 'Input',
  },
  {
    field: 'domain1',
    label: '文件域名1',
    rules: rules.rule('http', true),
    component: 'Input',
  },
];

const domainField = {
  endpointValue: 'endpointValue',
  domain: 'domain'
};


const { prefixCls } = useDesign('config-storage')
const attrs: any = useAttrs({ excludeDefaultKeys: false });
const { formSchema, configKey } = attrs.value
console.log('configKey: ', configKey);
const count = ref(1)

const { createMessage } = useMessage();
const record = ref<any>({
  configValue: '{}',
  tenantId: '-1'
})

const newFormSchema = JSON.parse(JSON.stringify(formSchema))
domainFormSchema.forEach(e => newFormSchema.push(e))


const configFromProps : ConfigFormProps = {
  configKey: configKey,
  schemas: newFormSchema,
  labelWidth: 110,
  fieldValueChange: (configValue) => { initDomain(configValue.domains) }
}

const [registerVerifyModal, { openModal: openVerifyModal }] = useModal();
const { 
  registerForm, loading, isSensitive, validate, setFieldsValue, 
  handleSensitiveConfig, appendSchemaByField, removeSchemaByField
} = useConfigForm(configFromProps, emit)


const initDomain = (newDomains: Array<any>) => {
  console.log("domains", newDomains);
  handleCleanDomain()
  if (newDomains) {
    let data: any = {}
    for (let i = 1; i <= newDomains.length; i++) {
      if (i > 1) {
        handleAddDomain()
      }
      data[domainField.endpointValue + i] = newDomains[i - 1][domainField.endpointValue]
      data[domainField.domain + i] = newDomains[i - 1][domainField.domain]
    }
    setFieldsValue(data)
  }
}


const getEndpointValuePlaceholder = (field) => {
  return '请输入原端点' + field.replace('endpointValue', '')
}

const getDomainPlaceholder = (field) => {
  return '请输入文件域名' + field.replace('domain', '')
}

const handleAddDomain = () => {
  count.value++
  appendSchemaByField(
    {
      field: `endpointValue${count.value}`,
      component: 'Input',
      label: '原端点' + count.value,
      required: false,
      slot: 'addEndpointValue'
    },
    ''
  );
  appendSchemaByField(
    {
      field: `domain${count.value}`,
      component: 'Input',
      label: '文件域名' + count.value,
      rules: rules.rule('http', true),
      required: true,
      slot: 'addDomain'
    },
    ''
  );
}


//表单提交事件
async function handleSubmit() {
  try {
    loading.value = true
    let values = await validate()
    const newValues = Object.assign({}, values)

    // 处理端点域名配置, 将多个封装成数组
    const formDomainMap = new Map()
    for (const key in newValues) {
      if (key === 'domainDivider') {
        delete newValues[key] 
      }
      if (key.includes('endpointValue') || key.includes('domain')) {
        const groupId = key.replaceAll('endpointValue', '').replaceAll('domain', '')
        const domainItem = formDomainMap.get(groupId) || {}
        domainItem[key.replace(groupId, '')] = newValues[key]
        formDomainMap.set(groupId, domainItem)
        delete newValues[key]
      }
    }
    const domains =  Array.from(formDomainMap.values())

    const configValue: any = { ...newValues, domains }
    record.value.configValue = JSON.stringify(configValue)

    //提交表单
    await defHttp.post({
      url: configKey.api, params: {
        id: record.value.id,
        configKey: configKey.code,
        configName: configKey.code,
        configValue: record.value.configValue
      }
    });
    console.log("configValue: ", configValue);
    createMessage.success(`编辑成功`)
  } finally {
    loading.value = false
  }
}

const handleShowSensitive = () => {
  openVerifyModal(true, {})
}
const handleSubmitVerify = async (data) => {
  await handleSensitiveConfig(data)
}

const handleCleanDomain = () => {
  const currentCount = count.value
  for (let i = 2; i <= currentCount; i++) {
    removeSchemaByField([`${domainField.domain}${i}`, `${domainField.endpointValue}${i}`]);
    count.value--
  }
}

const handleRemoveDomain = (field) => {
  const fieldCount = field.replace(domainField.domain, '').replace(domainField.endpointValue, '')
  removeSchemaByField([`${domainField.domain}${fieldCount}`, `${domainField.endpointValue}${fieldCount}`]);
  count.value--
}
</script>


<style lang="less" scoped>
@import '../../style.less';

@prefix-cls: ~'@{namespace}-config-storage';
.@{prefix-cls} {
  width: 750px;
  &-submit {
    margin-left: 110px;
  }
}

.file-config-alert {
  margin-bottom: 10px;
}

.dynamic-delete-button {
  cursor: pointer;
  position: relative;
  left: 5px;
  top: 4px;
  font-size: 24px;
  color: #999;
  transition: all 0.3s;
}

.dynamic-delete-button:hover {
  color: #777;
}

.dynamic-delete-button[disabled] {
  cursor: not-allowed;
  opacity: 0.5;
}
</style>
